//
//  ProvinceCityController.swift
//  SlaughterClient
//
//  Created by Ken on 2020/2/14.
//  Copyright © 2020 zwb. All rights reserved.
//  本地省市区控件

import UIKit
import JJCollectionViewRoundFlowLayout_Swift

enum CitySelectType {
    case city   // 选城市
    case proCityDict // 选省市区
}
enum CitySelectMode {
    case single
    case multi
}


class ProvinceCityController: UIViewController {
    
    init(selectType: CitySelectType,selectMode:CitySelectMode = .single) {
        super.init(nibName: nil, bundle: nil)
        self.selectType = selectType
        self.selectMode = selectMode

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var multiArr:[(String,String,String)] = []
    lazy var collectionView:UICollectionView = {
        // 1.创建layout
        let sectionW = self.view.ks_width - 24
        let layout = JJCollectionViewRoundFlowLayout_Swift()
        layout.itemSize = CGSize(width: sectionW/4 - 0.5, height: 40)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: 18, left: 12, bottom: 16, right: 12)
        
        // 2.创建UICollectionView
        let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        v.backgroundColor = .white
        v.showsHorizontalScrollIndicator = false
        
        v.register(ProCitySelectCell.self, forCellWithReuseIdentifier: ProCitySelectCell.identifier)
 
        return v
    }()
    
    var table1:UITableView!
    var table2:UITableView!
    var table3:UITableView!
    
    var province = ""
    var city = ""
    var district = ""
    
    var citySelectClosure:((String,String)->())?
    var tripleSelectClosure:((String,String,String)->())?
    var multiTripleSelectClosure:(([(String,String,String)])->())?

    var selectType = CitySelectType.city
    var selectMode = CitySelectMode.single

    var cityArr = [String]()
    var districtArr = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "城市选择"
        let leftBtn = UIButton.creat4Item(title: "返回") { _ in
           self.closeAction()
       }
        let left = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = left
        
        if selectMode == .multi {
            let rightBtn = UIButton.creat4Item(title: "确定") { _ in
                guard self.multiArr.count > 0 else {
                    KSToast("未选择")
                    return
                }
                if let clo = self.multiTripleSelectClosure {
                    clo(self.multiArr)
                }
                
                
                self.closeAction()
           }
            let right = UIBarButtonItem(customView: rightBtn)
            self.navigationItem.rightBarButtonItem = right
        }
        
        
        
        cityArr = cityDic[provinceArr[0]]!
        districtArr = areaDic[cityArr[0]].isSome ? areaDic[cityArr[0]]! : [""]
        
        var ccH:CGFloat = 0
        if selectMode == .multi {
             ccH = 180
            collectionView.dataSource = self
            collectionView.delegate = self
            self.view.addSubview(collectionView)
            collectionView.snp.makeConstraints { make in
                make.left.right.top.equalToSuperview()
                make.height.equalTo(ccH)
            }
        }
        
       
        
        table1 = UITableView(frame: CGRect(x:0,y: ccH,width: 110,height: KSGlobal.screenH))
        table1.delegate = self
        table1.dataSource = self
        self.view.addSubview(table1)
        
        table2 = UITableView(frame: CGRect(x:111,y: ccH,width: KSGlobal.screenW - 111,height: KSGlobal.screenH))
        table2.tableFooterView = UIView()
        table2.delegate = self
        table2.dataSource = self
        self.view.addSubview(table2)
        
        
        table1.register(UITableViewCell.self, forCellReuseIdentifier: "provinceCell_1")
        table2.register(UITableViewCell.self, forCellReuseIdentifier: "cityCell_2")
        
        if self.selectType == .city {
            
        } else {
            table3 = UITableView(frame: CGRect(x:222,y: ccH,width: KSGlobal.screenW - 222,height: KSGlobal.screenH))
            table3.tableFooterView = UIView()
            table3.delegate = self
            table3.dataSource = self
            self.view.addSubview(table3)
            
            table3.register(UITableViewCell.self, forCellReuseIdentifier: "districtCell_3")
        }
        
        
    }
    func closeAction() {
        if self.navigationController!.viewControllers.count > 1 { // 说明是push过来的
            self.navigationController?.popViewController(animated: true)
        } else {
            self.dismiss(animated: true, completion: {
            })
        }
    }
}

extension ProvinceCityController:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if tableView == table1 {
            return provinceArr.count
        } else if tableView == table2 {
            return cityArr.count
        } else {
            return districtArr.count
        }
        
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView == table1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "provinceCell_1", for: indexPath)
            cell.textLabel?.text = provinceArr[indexPath.row]
            
            
            return cell
        } else if  tableView == table2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cityCell_2", for: indexPath)
            cell.textLabel?.text = cityArr[indexPath.row]
            
            
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "districtCell_3", for: indexPath)
            cell.textLabel?.text = districtArr[indexPath.row]
            
            return cell
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        

        if tableView == table1 {
            cityArr = cityDic[provinceArr[indexPath.row]]!
            province = provinceArr[indexPath.row]
            city = ""
            district = ""
            districtArr.removeAll()
            self.table2.reloadData()
            self.table3.reloadData()
            
        } else if tableView == table2 {
            
            city = cityArr[indexPath.row]
            district = ""
            
            if self.selectType == .city  {
                if let clo = citySelectClosure {
                    clo(province,city)
                }
                self.closeAction()
            } else {
                if areaDic[cityArr[indexPath.row]].isSome {
                    districtArr =   areaDic[cityArr[indexPath.row]]!
                    self.table3.reloadData()
                } else {
                    if selectMode == .multi {
                        self.multiArr.append((province,city,""))
                        self.collectionView.reloadData()
                    } else {
                        if let clo = tripleSelectClosure {
                            clo(province,city,"")
                        }
                        self.closeAction()
                    }
                    
                    
                }
                
            }
            
        } else {
            
            if city == "" {
                tableView.deselectRow(at: indexPath, animated: false)
                return
            }
            
            district = districtArr[indexPath.row]
            if selectMode == .multi {
                self.multiArr.append((province,city,district))
                self.collectionView.reloadData()
            } else {
                
                if let clo = tripleSelectClosure {
                    clo(province,city,district)
                }
                self.closeAction()
            }
          
        }
    }
    
}
// MARK: - 代理和数据源
extension ProvinceCityController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    
//    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//        
//        let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FunctionCenterHeader.identifier, for: indexPath) as! FunctionCenterHeader
//        header.titleLabel.text = self.tempItemList[indexPath.section].0
//        
//        return header
//        
//        
//    }
//    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
//        
//        return CGSize(width: KSGlobal.screenW, height: 40)
//    }
    
    
//    func numberOfSections(in collectionView: UICollectionView) -> Int {
//        return self.tempItemList.count
//    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return multiArr.count
        
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProCitySelectCell.identifier, for: indexPath as IndexPath) as! ProCitySelectCell
        let shows = self.multiArr[indexPath.row].2 != "" ? self.multiArr[indexPath.row].2 : self.multiArr[indexPath.row].1
        cell.title.text = shows
  
         return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
 
        self.multiArr.remove(at: indexPath.row)
        self.collectionView.reloadData()
    }
    
    
    
    
}
extension ProvinceCityController : JJCollectionViewDelegateRoundFlowLayout_Swift {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 12, left: 12, bottom: 12, right: 12)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        let model = JJCollectionViewRoundConfigModel_Swift.init()
        model.cornerRadius = 8
        model.backgroundColor = UIColor(kshex:"#f9f9f9")
        
        
        return model;
        
    }
}
